#include "STC8G.H"
#include "intrins.h"
#include "delay.h"
#include "hardiic.h"
#define uchar unsigned char
#define uint unsigned int

/******************************************************
 * 
 *                      LCD1602代码
 * 
*******************************************************/
#define ADDR 0X4E //地址码 0X4E PCF8574 T;0X7E PCF8574 AT
/**
 * @brief	1602发送命令：命令或者数据
 * @param	dat:
 * @retval	None
 */
void LCDWriteData(uchar dat)
{
        Start();        //发送起始命令
        SendData(ADDR); //发送设备地址+写命令
        RecvACK();      //等待完成
        SendData(dat);  //发送命令
        RecvACK();      //等待完成
        Stop();         //结束
}
/**
 * @brief	写命令
 * @param	com:将要被写入的命令
 * @retval	None
 */
void lcd_write_com(uchar com) //写命令函数
{
        uchar com1, com2;
        com1 = com | 0x0f;
        LCDWriteData(com1 & 0xfc);
        delay2ms();
        LCDWriteData(com1 & 0xf8);
        com2 = com << 4;
        com2 = com2 | 0x0f;
        LCDWriteData(com2 & 0xfc);
        delay2ms();
        LCDWriteData(com2 & 0xf8);
}
/**
 * @brief	写数据
 * @param	date:将要被写入的数据
 * @retval	None
 */
void lcd_write_date(uchar date) //写数据函数
{
        uchar date1, date2;
        date1 = date | 0x0f;
        LCDWriteData(date1 & 0xfd);
        delay2ms();
        LCDWriteData(date1 & 0xf9);
        date2 = date << 4;
        date2 = date2 | 0x0f;
        LCDWriteData(date2 & 0xfd);
        delay2ms();
        LCDWriteData(date2 & 0xf9);
}
/**
 * @brief	初始化LCD1602
 * @param	
 * @retval	None
 */
void lcd_init()
{
        lcd_write_com(0x33); //原来1602初始化成4位数据线之前必需先初始化成8位(此时命令发送方式是8位格式,但数据线只需接4位)
        delay6ms();
        lcd_write_com(0x32); //然后再改到4位线宽,这样初始化才稳定
        delay6ms();
        lcd_write_com(0x28); //4位总线，双行显示，显示5×7的点阵字符
        delay6ms();
        lcd_write_com(0x01); //清屏
        delay6ms();
        lcd_write_com(0x06); //字符进入模式：屏幕不动，字符后移
        delay6ms();
        // lcd_write_com(0x0c); //显示开，关光标
        lcd_write_com(0x0f); //显示开,开光标,光标闪烁
        delay6ms();
}
/**
 * @brief	显示字符串
 * @param	x:1,2 y:1,2  str输出内容
 * @retval	None
 */
void lcd_show_string(unsigned char x, unsigned char y, unsigned char *str)
{
        if (x == 1)
        {
                lcd_write_com(0x80 | y - 1);
        }
        if (x == 2)
        {
                lcd_write_com(0xc0 | y - 1);
        }
        //输出字符串
        while (*str != '\0')
        {
                lcd_write_date(*str);
                str++;
        }
}
void main()
{
        uchar i = 0;
        uchar str[16];
        hardiic_init(4); //选择第四组I2C(P3.2/SCL, P3.3/SDA)
        lcd_init();      //初始化LCD
        while (1)
        {
                lcd_write_com(0x01); //清屏
                str[i] = i + '0';
                lcd_write_date(str[i]);
                if (i > 16)
                {
                        lcd_show_string(2, 1, str);
                        i = 0;
                        delay(500);
                }
                i++;
                delay(500);
        }
}
